<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { $t } from '@/locales';
import { loginModuleRecord } from '@/constants/app';
import { useRouterPush } from '@/hooks/common/router';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import { getCaptchaImage } from '@/service/api/auth';
import type { LoginParams } from '@/service/api/auth';

defineOptions({
  name: 'PwdLogin'
});

const authStore = useAuthStore();
const { toggleLoginModule } = useRouterPush();
const { formRef, validate } = useNaiveForm();

interface FormModel {
  username: string;
  password: string;
  code: string | null;
  uuid: string;
  method: string;
}

const model = reactive<FormModel>({
  username: 'Soybean',
  password: '123123',
  code: null,
  uuid: '',
  method: '1'
});

const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  const { formRules } = useFormRules();
  return {
    method: [],
    code: [],
    username: formRules.username,
    password: formRules.pwd,
    uuid: []
  };
});

const captchaUrl = ref('');

const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    const { username, password, code, uuid } = model;
    const loginParams: LoginParams = {
      username,
      password,
      method: '1'
    };
    if (code !== null) {
      loginParams.code = code;
      loginParams.uuid = uuid;
    }
    await authStore.login(loginParams);
  } catch {
    // Validation failed
  }
};

async function refreshCaptcha() {
  const { data } = await getCaptchaImage();
  if (data) {
    captchaUrl.value = data.img;
    model.uuid = data.sessionId;
  }
}

refreshCaptcha();

type AccountKey = 'super' | 'admin' | 'user';

interface Account {
  key: AccountKey;
  label: string;
  username: string;
  password: string;
}

const accounts = computed<Account[]>(() => [
  {
    key: 'super',
    label: $t('page.login.pwdLogin.superAdmin'),
    username: 'Super',
    password: '123456'
  },
  {
    key: 'admin',
    label: $t('page.login.pwdLogin.admin'),
    username: 'Admin',
    password: '123456'
  },
  {
    key: 'user',
    label: $t('page.login.pwdLogin.user'),
    username: 'User',
    password: '123456'
  }
]);

const handleAccountLogin = async () => {
  const { username, password, code, uuid } = model;
  const loginParams: LoginParams = {
    username,
    password,
    method: 'pwd'
  };
  if (code !== null) {
    loginParams.code = code;
    loginParams.uuid = uuid;
  }
  await authStore.login(loginParams);
};
</script>

<template>
  <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false" @keyup.enter="handleSubmit">
    <NFormItem path="username">
      <NInput v-model:value="model.username" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </NFormItem>
    <NFormItem path="password">
      <NInput
        v-model:value="model.password"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </NFormItem>
    <NFormItem path="code">
      <div class="flex items-center gap-4px w-full">
        <NInput
          v-model:value="model.code"
          type="text"
          :placeholder="$t('page.login.common.codePlaceholder')"
          class="flex-1 transition-all duration-300 max-w-none"
        />
        <img
          :src="captchaUrl"
          alt="验证码"
          class="h-40px transition-all duration-300 hover:opacity-90 active:scale-95 w-[140px] md:w-[120px] sm:w-[100px] rounded-md"
          @click="refreshCaptcha"
        />
      </div>
    </NFormItem>
    <NSpace vertical :size="24">
      <div class="flex-y-center justify-between">
        <NCheckbox>{{ $t('page.login.pwdLogin.rememberMe') }}</NCheckbox>
        <NButton quaternary @click="toggleLoginModule('reset-pwd')">
          {{ $t('page.login.pwdLogin.forgetPassword') }}
        </NButton>
      </div>
      <NButton type="primary" size="large" round block :loading="authStore.loginLoading" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </NButton>
      <div class="flex-y-center justify-between gap-12px">
        <NButton class="flex-1" block @click="toggleLoginModule('code-login')">
          {{ $t(loginModuleRecord['code-login']) }}
        </NButton>
        <NButton class="flex-1" block @click="toggleLoginModule('register')">
          {{ $t(loginModuleRecord.register) }}
        </NButton>
      </div>
      <NDivider class="text-14px text-#666 !m-0">{{ $t('page.login.pwdLogin.otherAccountLogin') }}</NDivider>
      <div class="flex-center gap-12px">
        <NButton v-for="item in accounts" :key="item.key" type="primary" @click="handleAccountLogin(item)">
          {{ item.label }}
        </NButton>
      </div>
    </NSpace>
  </NForm>
</template>

<style scoped></style>
